// 样式-数据-可拖拉拽树
import React from 'react';
import { Input, TreeSelect } from 'antd';
import { SearchOutlined, PartitionOutlined }  from '@ant-design/icons';
import { getDataTree } from 'src/services/AnalyseManage';
import { Scrollbars } from 'react-custom-scrollbars';
import Tree from './Tree';
import { DECIMAL_TYPES, INT_TYPES, WD_TYPE, DL_TYPE } from '../../EnumConfig';
import { getFirstTable } from 'src/libs/utils';

const colorBlue = { color: '#167DDC' };
const colorGreen = { color: '#87BD25' };

interface IProps {
	setCurrentResult: any;
	pageId: string;
	config: any;
	currentType: string;
	onValueChange: ( values: any ) => void;
	selectDisabled?: boolean;
	isDataResource?: string; // Y/N 默认N
	dataTables: Array<any>;
}

class ModelDataTree extends React.Component<IProps> {
	state: any = {
		tables: [],
		tree: [],
		currentDragType: '',
		wdFolderId: '',
		dlFolderId: '',
		tableCode: '',
		filterTree: [],
		expandedKeys: [],
		keyWord: '',
	};

	timer = null;
	dataList = [];

	initCurrentTableCode = () => {
		const tables = this.props.dataTables;

		if ( tables.length > 0 ) {
			let defaultValue = '';
			const tableCode = this.props.config.data.tableCode;
			if ( tableCode !== '' ) {
				// tableCode 如果存在
				this.setState( {
					tableCode,
					treeSelectExpandedKeys: [ tableCode ],
				} );
				this.initColumn( tableCode );
			}

			if ( !tableCode ) {
				// 如果不存在 则需要初始化为第一个 tableCode
				const { onValueChange } = this.props;

				defaultValue = tables && tables.length > 0 ? getFirstTable( tables ) : '';

				this.setState( { tableCode: defaultValue, treeSelectExpandedKeys: [ defaultValue ] } );
				onValueChange( { tableCode: defaultValue } );
			}
		}
	};

	initColumn = async ( tableCode: string ) => {
		if ( !tableCode ) return;

		const { isDataResource } = this.props;

		const reqParams = {
			// pageId: pageId,
			isDataResource: isDataResource || 'N',
			modelId: tableCode,
		};

		let response = await getDataTree( reqParams );

		let enumConfig = {
			WD: WD_TYPE,
			DL: DL_TYPE,
		};

		if ( response.data && response.data.success ) {
			let dates = response.data.data;
			let treeData = [];
			dates.forEach( ( item: any ) => {
				let child = this.buildChild( item, enumConfig[item.type] );
				treeData.push( child );
			} );

			//默认展开所有树
			const loopTree = ( tree ) => {
				let list = [];
				tree.forEach( node => {
					list.push( node );
					if ( node.children && node.children.length ) {
						list.push( ...loopTree( node.children ) );
					}
				} );
				return list;
			};
			this.dataList = loopTree( treeData );
			let expandedKeys = this.dataList.map( o => o.id );

			this.setState( { 
				tree: treeData, 
				filterTree: treeData, 
				wdFolderId: treeData[0].id, 
				dlFolderId: treeData[1].id,
				keyWord: '',
				expandedKeys,
			} );
		}
	};

	buildChild = ( item: any, type: string ) => {
		let childs = [];
		( item.children || [] ).forEach( ( childrenItem: any ) => {
			let child = this.buildChild( childrenItem, type );
			childs.push( child );
		} );
		return {
			...item,
			key: item.id,
			title: item.desc ? item.desc : item.name,
			children: childs,
			modelType: type,
			// icon: <CarryOutOutlined />,
		};
	};

	componentDidUpdate( prevProps ) {
		if ( prevProps.config.key !== this.props.config.key ) {
			const tableCode = this.props.config.data.tableCode;
			this.setState( { tableCode: tableCode }, () => {
				this.initCurrentTableCode();
			} );
		}
		let tableCode = this.props.config.data.tableCode;
		if ( tableCode && prevProps.config.data.tableCode !== tableCode ) {
			if ( !tableCode ) {
				tableCode = this.props.dataTables && this.props.dataTables.length > 0 ? this.props.dataTables[0] : '';
			}
			this.setState( { tableCode: tableCode }, () => {
				this.initColumn( tableCode );
			} );
		}

		//	设置默认展开的文件夹
		if( prevProps.dataTables.length === 0 && this.props.dataTables.length > 0 ) {
			this.initCurrentTableCode();
		}
	}

	handleChange = ( value ) => {
		const { onValueChange, config } = this.props;
		// 清空数据
		const types = [ 'pieType', 'tableType', 'columnType', 'lineType', 'wordCloudType', 'scatterType', 'mapType', 'bulletType' ];
		let data = JSON.parse( JSON.stringify( config.data ) );
		for ( let p in data ) {
			if ( types.includes( p ) ) {
				continue;
			}
			data[p] = undefined;
		}
		onValueChange( { ...data, tableCode: value } );
		this.setState( { tableCode: value } );
	};

	handleSearchChange = ( e ) => {
		let keyWord = e.target.value;
		this.setState( { keyWord } );
		// console.log( '== keyWord ==', keyWord );
		if ( this.timer ) clearTimeout( this.timer );
		this.timer = setTimeout( () => {
			this.dataList = [];
			let filterTree = this.loopTreeList( keyWord, this.state.tree );
			let expandedKeys = this.dataList.map( o => o.id );
			this.setState( {
				filterTree,
				expandedKeys,
			} );
		}, 500 );
	};

	loopTreeList = ( keyWord, data ) => {
		if ( !keyWord ) return data;
		let list = data.map( node => {
			if ( node.children && node.children.length ) {
				this.dataList.push( node );
				return {
					...node,
					children: this.loopTreeList( keyWord, node.children ),
				};
			} else {
				let str = `${node.name} ${node.desc}`.toLowerCase();
				if ( ~str.indexOf( keyWord ) ) {
					this.dataList.push( node );
					return node;
				} else {
					return null;
				}
			}
		} );

		list = list.filter( node => node !== null );
		
		return list;
	};

	onExpand = ( expandedKeys ) => {
		this.setState( {
			expandedKeys,
		} );
	};

	render() {
		return (
			<div style={{ height: '100%' }}>

				<div style={{ width: '100%', height: 40 }}>
					<TreeSelect
						treeDefaultExpandedKeys={this.state.treeSelectExpandedKeys}
						showSearch
						allowClear
						treeIcon
						treeNodeFilterProp='title'
						treeData={this.props.dataTables}
						disabled={ !!this.props.selectDisabled } 
						style={{ width: '100%' }} 
						onChange={this.handleChange} 
						value={this.state.tableCode}>
					</TreeSelect>
				</div>

				<div style={{ width: '100%', height: 40 }}>
					<Input placeholder="请输入" 
						allowClear 
						value={this.state.keyWord}
						onChange={ this.handleSearchChange }
						prefix={<SearchOutlined />} />
				</div>

				<Scrollbars style={{ height: 'calc(100% - 80px)' }}>
					<Tree
						setCurrentResult={this.props.setCurrentResult}
						data={this.state.filterTree}
						icon={( props: any ) => {
							const { dataType, childrenType, parentId } = props;
							if ( !dataType && parentId === '0' ) {
								// 如果是根目录
								return <span className={'iconfont bdhwenjianjiaguanbi'}></span>;
							} else if( parentId !== '0' && childrenType === 'FOLDER' ) {
								// 自定义层级
								return <PartitionOutlined />;
							} else if ( [ 'TIME' ].indexOf( dataType.toUpperCase() ) !== -1 ) {
								// 时间
								return <span className={'iconfont bdhshijianriqi'} style={ colorBlue }></span>;
							} else if ( [ 'DATE', 'DATETIME', 'TIMESTAMP' ].indexOf( dataType.toUpperCase() ) !== -1 ) {
								// 日期
								return <span className={'iconfont bdhshijianriqi'} style={ colorBlue }></span>;
							} else if ( INT_TYPES.indexOf( dataType.toUpperCase() ) !== -1 ) {
								// 整数
								return <span className={'iconfont bdhzhengshu'} style={ colorGreen }></span>;
							} else if ( DECIMAL_TYPES.indexOf( dataType.toUpperCase() ) !== -1 ) {
								// 小数
								return <span className={'iconfont bdhzhengshubeifen'} style={ colorBlue }></span>;
							} else {
								// 字符串文本
								return <span className={'iconfont bdhwenben'} style={ colorGreen }></span>;
							}
						}}
						onExpand={ this.onExpand }
						expandedKeys={this.state.expandedKeys}
					></Tree>
				</Scrollbars>
			</div>
		);
	}
}

export default ModelDataTree;
